package com.flying.refdata.service;

import com.flying.refdata.model.equity.EquityInfo;
import com.flying.refdata.repository.equity.EquityInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class EquityService {
    @Autowired
    private EquityInfoRepository infoRepository;
    private Map<String, EquityInfo> infoCache = new ConcurrentHashMap<>();

    @PostConstruct
    private void buildCache() {
        List<EquityInfo> infos = infoRepository.findAll();
        for (EquityInfo info : infos) {
            infoCache.put(info.getCode(), info);
        }
    }

    public EquityInfo getEquityInfo(String code) {
        if (infoCache.containsKey(code)) return infoCache.get(code);
        EquityInfo info = infoRepository.findByCode(code);
        if (info == null) return null;
        infoCache.put(code, info);
        return info;
    }

    private synchronized EquityInfo addEquityInfo(String code, String name) {
        // double check.
        EquityInfo info = getEquityInfo(code);
        if (info == null) {
            info = new EquityInfo();
            info.setCode(code);
            info.setName(name);
            info = infoRepository.save(info);
            infoCache.put(info.getCode(), info);
        }
        return info;
    }

    public EquityInfo getOrSaveEquityInfo(String code, String name) {
        EquityInfo info = getEquityInfo(code);
        if (info == null) {
            info = addEquityInfo(code, name);
        }
        return info;
    }

    public Collection<EquityInfo> getAll() {
        return infoCache.values();
    }
}